<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/9/29
 * Time: 22:10
 */
class Stock
{
    private $token;

    /**
     * 设置登陆
     */
    public function __construct()
    {
        import('Com.Requests');
        Requests::register_autoloader();
        self::getToken();
    }

    /**
     * 获取股票实时行情
     */
    public function GetQuote($code)
    {
        $codes = is_array($code)?implode(',',$code):$code;
        $url = 'http://webhq.700000.cc:5432/GetQuote.ashx?symbol='.$codes;
        try {
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }catch (Requests_Exception $e){
            self::getToken();
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }
        $data = str_replace(['hq_str_','"'],'',$rep->body);
        $data = explode(';',$data);
        foreach($data as $key=>$value){
            unset($data[$key]);
            if(!empty($value)) {
                $value           = explode('=', trim($value));
                $data[$value[0]] = explode(',', $value[1]);
            }
        }
        return $data;
    }

    /**
     * 大盘数据
     */
    public function IndexUpdown()
    {
        $type_array = [
            1 => '上证A股',
            2 => '上证B股',
            4 => '深圳A股',
            5 => '深圳B股',
            6 => '上证债券',
            7 => '深圳债券',
            8 => '上证基金',
            9 => '深证基金'
        ];
        $url        = 'http://webhq.700000.cc:5432/GetIndexUpdown.ashx';
        try {
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }catch (Requests_Exception $e){
            self::getToken();
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }
        $data       = str_replace(['indexupdown_str=["', '"]'], '', $rep->body);
        $data       = explode('","', $data);
        foreach ($data as $k => $v) {
            $v = explode(',', $v);
            $data[$k]=['name'=>$type_array[$v[0]],'up'=>$v[1],'down'=>$v[2],'plate'=>$v[3],'rental'=>number_format($v[4],0,'','')];
        }
        return $data;
    }

    /**
     * 强制更新
     */
    public function setToken()
    {
        $url = 'http://webhq.700000.cc:5432/ManageAuth.ashx?p=iq{uyg}iq{uyg032';
        $rep = Requests::get($url,'',['timeout'=>30]);
        $this->token = $rep->cookies;
        S('stock_cookie', $this->token, 1740);
    }

    /**
     * 获取所有数据包
     */
    public function GetBlock($type)
    {
        $url  = 'http://webhq.700000.cc:5432/GetBlock.ashx?stocktype=' . $type;
        try {
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }catch (Requests_Exception $e){
            self::getToken();
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }
        $data = str_replace(['datas=["', ']', '"]', 'quotes=["'], '', $rep->body);
        $data = str_replace('datas=[', '', $data);
        $data = str_replace('""', '","', $data);
        $data = explode('","', $data);
        foreach ($data as $k => $v) {
            $v = explode(',', $v);
            unset($v[4]);
            $v[2] = str_replace(' ', '', $v[2]);
            if ($type > 18) {
                $t    = $v[1];
                $v[1] = $v[2];
                $v[2] = $t;
            }
            $v[3] = isset($v[3])?$v[3]:'';
            $v[4]     = pinyin($v[2]);
            $v[5]     = pinyin($v[2], true);
            $data[$k] = $v;
        }

        return $data;
    }

    private function getToken()
    {
        $cookie = S('stock_cookie');
        if (empty($cookie)) {
            $url = 'http://webhq.700000.cc:5432/ManageAuth.ashx?p=iq{uyg}iq{uyg032';
            try {
                $rep = Requests::get($url, '', ['timeout' => 30]);
            }catch (Requests_Exception $e){
                $json = json_encode(['code'=>__LINE__,'msg'=>'数据接口故障，请稍后再试']);
                exit($json);
            }
            S('stock_cookie', $rep->cookies, 1740);
            $this->token = $rep->cookies;
        } else {
            $this->token = $cookie;
        }
    }

    /**
     * 获取股票分时数据
     * 返回近一天的数据
     *
     * @param string $code 股票代码
     * @param int    $len  返回长度
     */
    public function GetMinuteData($code, $len = 10)
    {
        $url = 'http://webhq.700000.cc:5432/GetMinuteData.ashx?SYMBOL='.$code.'&datalen='.$len;
        try {
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }catch (Requests_Exception $e){
            self::setToken();
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }
        $data = str_replace(['minute_str_'.strtoupper($code),'["',']','='],'',$rep->body);
        $data = explode('",',$data);
        foreach($data as $k=>$val){
            if(empty($val)){
                unset($data[$k]);
            }
        }
        return $data;
    }

    /**
     * 获取股票K线
     * @param string    $code 股票代码
     * @param int $linty K线类型 0：五分钟K线，1：15分钟K线， 2：30分钟K线， 3：60分钟K线，4：日K线，5：周线，6：月线
     * @param int $len 多少条k线数据
     */
    public function GetKLine($code,$linty=0,$len=10){
        $url='http://webhq.700000.cc:5432/GetKLine.ashx?symbol='.$code.'&klinetype='.$linty.'&datalen='.$len;
        try {
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }catch (Requests_Exception $e){
            self::getToken();
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }

    }
    
    /**
     * 获取行情报价牌
     */
    public function GetQuoteList($stocktype,$OrderKey,$OrderType=0,$PageSize=10){
        $url='http://webhq.700000.cc:5432/GetQuoteList.ashx?stocktype='.$stocktype.'&OrderKey='.$OrderKey.'&OrderType='.$OrderType.'&StartIndex=0&PageSize='.$PageSize;
        try {
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }catch (Requests_Exception $e){
            self::getToken();
            $rep = Requests::get($url, '', ['cookies' => $this->token,'timeout'=>30]);
        }
        $data = str_replace(['quotes=["','"]'],'',$rep->body);
        $data = explode('","',$data);
        return $data;
    }
}